package com.common.app.widget.calendardialog

import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import com.common.app.R
import com.common.app.utls.TimeUtils
import java.text.DateFormatSymbols
import java.util.Calendar
import java.util.Date
import java.util.Locale


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：30/5/2025
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class CusCalendarView : LinearLayout {
    // ************************************************************************************************************************************************************************
    // * Attributes
    // ************************************************************************************************************************************************************************
    // View
    private var context: Context
    private var dateTitle: TextView? = null
    private var leftButton: ImageView? = null
    private var rightButton: ImageView? = null
    private var rootView: View? = null
    private var robotoCalendarMonthLayout: ViewGroup? = null

    // Class
    private var onCalendarClickListener: OnCalendarClickListener? = null
    private var currentCalendar: Calendar? = null
    private var tempCalendar: Calendar? = null
    private var lastSelectedDayCalendar: Calendar? = null

    /**
     * 当前选中的日期
     */
    private var currentSelectedDay: Calendar? = null

    /**
     * 是否限制只显示两个月
     */
    private var isLimitMonth = false
    private var shortWeekDays = true

    /**
     * 是否异常右边按钮
     */
    private val isHideRightBtn = true

    // ************************************************************************************************************************************************************************
    // * Initialization methods
    // ************************************************************************************************************************************************************************
    constructor(context: Context) : super(context) {
        this.context = context
        onCreateView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        this.context = context
        if (isInEditMode) {
            return
        }
        onCreateView()
    }

    private fun onCreateView(): View? {
        val inflate = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        rootView = inflate.inflate(R.layout.cus_calendar_picker_layout, this, true)
        findViewsById(rootView)
        setUpEventListeners()
        setUpCalligraphy()
        checkRightButtonVisibility() // 添加这一行
        return rootView
    }

    fun isLimitMonth(): Boolean {
        return isLimitMonth
    }

    fun setLimitMonth(limitMonth: Boolean) {
        isLimitMonth = limitMonth
        if (!isHideRightBtn) {
            if (isLimitMonth) {
                rightButton?.visibility = INVISIBLE
                val calendar: Calendar = Calendar.getInstance()
                if (currentCalendar?.get(Calendar.MONTH) != calendar.get(Calendar.MONTH)) {
                    rightButton?.visibility = VISIBLE
                }
            } else {
                rightButton?.visibility = VISIBLE
            }
        }
    }

    private fun findViewsById(view: View?) {
        robotoCalendarMonthLayout =
            view?.findViewById<View>(R.id.robotoCalendarDateTitleContainer) as ViewGroup
        leftButton = view.findViewById<View>(R.id.leftButton) as ImageView
        rightButton = view.findViewById<View>(R.id.rightButton) as ImageView
        if (!isHideRightBtn) {
            if (isLimitMonth) {
                rightButton?.visibility = INVISIBLE
            } else {
                rightButton?.visibility = VISIBLE
            }
        }
        dateTitle = view.findViewById<View>(R.id.monthText) as TextView
        for (i in 0..41) {
            val inflate =
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            val weekIndex = i % 7 + 1
            val dayOfTheWeekLayout =
                view.findViewWithTag<View>(DAY_OF_THE_WEEK_LAYOUT + weekIndex) as ViewGroup

            // Create day of the month
            val dayOfTheMonthLayout: View = inflate.inflate(R.layout.cus_calendar_day_of_the_month_layout, null)
            val dayOfTheMonthText = dayOfTheMonthLayout.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT)
            val dayOfTheMonthBackground = dayOfTheMonthLayout.findViewWithTag<View>(
                DAY_OF_THE_MONTH_BACKGROUND
            )
            val dayOfTheMonthCircleImage1 = dayOfTheMonthLayout.findViewWithTag<View>(
                DAY_OF_THE_MONTH_CIRCLE_IMAGE_1
            )
            val dayOfTheMonthCircleImage2 = dayOfTheMonthLayout.findViewWithTag<View>(
                DAY_OF_THE_MONTH_CIRCLE_IMAGE_2
            )

            // Set tags to identify them
            val viewIndex = i + 1
            dayOfTheMonthLayout.tag = DAY_OF_THE_MONTH_LAYOUT + viewIndex
            dayOfTheMonthText.tag = DAY_OF_THE_MONTH_TEXT + viewIndex
            dayOfTheMonthBackground.tag = DAY_OF_THE_MONTH_BACKGROUND + viewIndex
            dayOfTheMonthCircleImage1.tag = DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 + viewIndex
            dayOfTheMonthCircleImage2.tag = DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 + viewIndex
            dayOfTheWeekLayout.addView(dayOfTheMonthLayout)
        }
    }

    private fun setUpEventListeners() {
        leftButton?.setOnClickListener {
            onCalendarClickListener?.let { onCalendarClickListenerIt->
                // Decrease month
                currentCalendar?.add(Calendar.MONTH, -1)
                lastSelectedDayCalendar = null
                updateView()
                onCalendarClickListenerIt.onLeftButtonClick()
                updateMark()
                if (isLimitMonth) {
                    leftButton?.visibility = INVISIBLE
                    rightButton?.visibility = VISIBLE
                }
                checkRightButtonVisibility()
            }
        }

        rightButton?.setOnClickListener {
            onCalendarClickListener?.let { onCalendarClickListenerIt ->
                // Increase month
                currentCalendar?.add(Calendar.MONTH, 1)
                lastSelectedDayCalendar = null
                updateView()
                onCalendarClickListenerIt.onRightButtonClick()
                updateMark()
                if (isLimitMonth) {
                    leftButton?.visibility = VISIBLE
                    rightButton?.visibility = INVISIBLE
                }
                checkRightButtonVisibility()
            }
        }
    }

    /**
     * 当前日期的开始时间毫秒值
     */
    private var currentTimeMillis: Long = 0

    /**
     * 初始化当前时间
     */
    private fun setUpCalligraphy() {
        // Initialize calendar for current month
        val currentCalendar: Calendar = Calendar.getInstance()
        tempCalendar = Calendar.getInstance()
        setCalendar(currentCalendar)
        currentTimeMillis = TimeUtils.getTodayStart(currentCalendar.timeInMillis)
    }
    // ************************************************************************************************************************************************************************
    // * Auxiliary UI methods
    // ************************************************************************************************************************************************************************
    /**
     * 设置标题
     */
    private fun setUpMonthLayout() {
        currentCalendar?.let {
            var dateText: String = DateFormatSymbols(Locale.getDefault()).shortMonths[it.get(Calendar.MONTH)]
            dateText = dateText.substring(0, 1).uppercase(Locale.getDefault()) + dateText.subSequence(
                1,
                dateText.length
            )
            dateTitle?.text =
                java.lang.String.format("%s / %s", it.get(Calendar.YEAR), dateText)
        }
    }

    /**
     * 设置  周 栏的值
     */
    private fun setUpWeekDaysLayout() {
        currentCalendar?.let {
            var dayOfWeek: TextView
            var dayOfTheWeekString: String
            val weekDaysArray: Array<String> = DateFormatSymbols(Locale.getDefault()).shortWeekdays
            for (i in 1 until weekDaysArray.size) {
                dayOfWeek = rootView?.findViewWithTag<View>(DAY_OF_THE_WEEK_TEXT + getWeekIndex(i, it)) as TextView
                dayOfTheWeekString = weekDaysArray[i].replace("周", "")
                dayOfWeek.text = dayOfTheWeekString
            }
        }
    }

    private fun setUpDaysOfMonthLayout() {
        var dayOfTheMonthText: TextView?
        var circleImage1: View?
        var circleImage2: View?
        var dayOfTheMonthContainer: ViewGroup
        var dayOfTheMonthBackground: ViewGroup
        for (i in 1..42) {
            dayOfTheMonthContainer =
                rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_LAYOUT + i) as ViewGroup
            dayOfTheMonthBackground =
                rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_BACKGROUND + i) as ViewGroup
            dayOfTheMonthText =
                rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT + i) as TextView
            circleImage1 = rootView?.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 + i)
            circleImage2 = rootView?.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 + i)
            dayOfTheMonthText.visibility = INVISIBLE
            circleImage1?.visibility = INVISIBLE
            circleImage2?.visibility = GONE

            // Apply styles
            dayOfTheMonthText.setBackgroundResource(R.color.transparent)
            dayOfTheMonthText.setTypeface(null, Typeface.NORMAL)
            dayOfTheMonthText.setTextColor(ContextCompat.getColor(context, R.color.text_content))
            dayOfTheMonthContainer.setBackgroundResource(R.color.transparent)
            dayOfTheMonthContainer.setOnClickListener(null)
            dayOfTheMonthBackground.setBackgroundResource(R.color.transparent)
        }
    }

    /**
     * 设置天数
     */
    private fun setUpDaysInCalendar() {
        tempCalendar?.let { tempCalendarIt->

            val auxCalendar: Calendar = Calendar.getInstance(Locale.getDefault())
            auxCalendar.time = currentCalendar?.time
            auxCalendar.set(Calendar.DAY_OF_MONTH, 1)
            val firstDayOfMonth: Int = auxCalendar.get(Calendar.DAY_OF_WEEK)
            var dayOfTheMonthText: TextView
            var dayOfTheMonthContainer: ViewGroup
            var dayOfTheMonthLayout: ViewGroup

            // Calculate dayOfTheMonthIndex
            var dayOfTheMonthIndex = getWeekIndex(firstDayOfMonth, auxCalendar)
            run {
                var i = 1
                while (i <= auxCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                    dayOfTheMonthContainer =
                        rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_LAYOUT + dayOfTheMonthIndex) as ViewGroup
                    dayOfTheMonthText =
                        rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT + dayOfTheMonthIndex) as TextView
                    if (dayOfTheMonthText == null) {
                        break
                    }
                    dayOfTheMonthContainer.setOnClickListener(onDayOfMonthClickListener)
                    //            dayOfTheMonthContainer.setOnLongClickListener(onDayOfMonthLongClickListener);
                    dayOfTheMonthText.visibility = VISIBLE
                    dayOfTheMonthText.text = i.toString()
                    tempCalendarIt.set(Calendar.YEAR, auxCalendar.get(Calendar.YEAR))
                    tempCalendarIt.set(Calendar.MONTH, auxCalendar.get(Calendar.MONTH))
                    tempCalendarIt.set(Calendar.DAY_OF_MONTH, i)
                    tempCalendarIt.set(Calendar.HOUR_OF_DAY, 0)
                    tempCalendarIt.set(Calendar.MINUTE, 0)
                    tempCalendarIt.set(Calendar.SECOND, 0)
                    tempCalendarIt.set(Calendar.MILLISECOND, 0)
                    if (currentTimeMillis >= tempCalendarIt.timeInMillis) {
                        //可选范围(今天之前的可选)
                        dayOfTheMonthText.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.text_content
                            )
                        )
                    } else {
                        dayOfTheMonthText.setTextColor(
                            ContextCompat.getColor(
                                context,
                                R.color.text_content_week_c7
                            )
                        )
                        //今天之后的天数，不可选
                    }
                    i++
                    dayOfTheMonthIndex++
                }
            }
            for (i in 36..42) {
                dayOfTheMonthText =
                    rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT + i) as TextView
                dayOfTheMonthLayout =
                    rootView?.findViewWithTag<View>(DAY_OF_THE_MONTH_LAYOUT + i) as ViewGroup
                if (dayOfTheMonthText.visibility == INVISIBLE) {
                    dayOfTheMonthLayout.visibility = GONE
                } else {
                    dayOfTheMonthLayout.visibility = VISIBLE
                }
            }
        }
    }

    private fun markDayAsCurrentDay() {
        val nowCalendar: Calendar = Calendar.getInstance()
        if (nowCalendar.get(Calendar.YEAR) == currentCalendar?.get(Calendar.YEAR) && nowCalendar.get(
                Calendar.MONTH
            ) == currentCalendar?.get(Calendar.MONTH)
        ) {
            val currentCalendar: Calendar = Calendar.getInstance()
            currentCalendar.time = nowCalendar.time
            val dayOfTheMonthBackground = getDayOfMonthBackground(currentCalendar)
            dayOfTheMonthBackground.setBackgroundResource(R.drawable.cus_calendar_today_ring)
        }
    }

    fun getCurrentSelectedDay(): Calendar? {
        return currentSelectedDay
    }

    fun setSelectedDay(currentTimeMillis: Long) {
            //获取当前的
            var curMonth = 0
            currentCalendar?.let {
                curMonth = it.get(Calendar.MONTH)
            }
            val calendar: Calendar = Calendar.getInstance()
            calendar.time = Date(currentTimeMillis)
            currentSelectedDay = calendar
            //        Log.e("hdltag", "setSelectedDay(CalendarView.java:342):" + TimerUtils.getDateByCurrentTime(currentCalendar.getTimeInMillis()));
            currentSelectedDay?.let {
                if (curMonth == it.get(Calendar.MONTH)) { //当前月份才标记
                    // Log.e("hdltag", "setSelectedDay(CalendarView.java:343):当月，开始标记");
                    markDayAsSelectedDay(it)
                } else {
                    lastClearSelectedDay?.let {lastClearSelectedDayIt->
                        clearSelectedDay(lastClearSelectedDayIt)
                    }
                }
            }
    }

    private var lastClearSelectedDay: Calendar? = null

    private fun markDayAsSelectedDay(calendar: Calendar) {
        lastClearSelectedDay = calendar
        //        Log.e("hdltag", "markDayAsSelectedDay(CalendarView.java:351):标记这一天为选中了" + TimerUtils.getDateByCurrentTime(calendar.getTimeInMillis()));
        // Clear previous current day mark
        lastSelectedDayCalendar?.let {
            clearSelectedDay(it)
        }

        // Store current values as last values
        lastSelectedDayCalendar = calendar

        // Mark current day as selected
        val dayOfTheMonthBackground = getDayOfMonthBackground(calendar)
        dayOfTheMonthBackground.setBackgroundResource(R.drawable.cus_calendar_select_ring)
        val dayOfTheMonth = getDayOfMonthText(calendar)
        dayOfTheMonth.setTextColor(
            ContextCompat.getColor(
                context,
                R.color.white
            )
        )
        val circleImage1 = getCircleImage1(calendar)
        val circleImage2 = getCircleImage2(calendar)
        //        if (circleImage1.getVisibility() == VISIBLE) {
//            DrawableCompat.setTint(circleImage1.getDrawable(), ContextCompat.getColor(context, R.color.white));
//        }
        if (circleImage2.visibility == VISIBLE) {
            DrawableCompat.setTint(
                circleImage2.drawable,
                ContextCompat.getColor(context, R.color.white)
            )
        }
    }

    private fun clearSelectedDay(calendar: Calendar) {
            val dayOfTheMonthBackground = getDayOfMonthBackground(calendar)
            // If it's today, keep the current day style
            val nowCalendar: Calendar = Calendar.getInstance()
            if (nowCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR) && nowCalendar.get(
                    Calendar.DAY_OF_YEAR
                ) == calendar.get(Calendar.DAY_OF_YEAR)
            ) {
//                Log.e("hdltag", "clearSelectedDay(CalendarView.java:393):------------当月的----------");
                if (currentCalendar?.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)) {
                    dayOfTheMonthBackground.setBackgroundResource(R.drawable.cus_calendar_today_ring)
                } else {
                    dayOfTheMonthBackground.setBackgroundResource(R.color.transparent)
                }
            } else {
                dayOfTheMonthBackground.setBackgroundResource(R.color.transparent)
            }
            val dayOfTheMonth = getDayOfMonthText(calendar)
            dayOfTheMonth.setTextColor(
                ContextCompat.getColor(
                    context,
                    R.color.text_content
                )
            )
            val circleImage1 = getCircleImage1(calendar)
            val circleImage2 = getCircleImage2(calendar)
            if (circleImage1.visibility == VISIBLE) {
                DrawableCompat.setTint(
                    circleImage1.drawable,
                    ContextCompat.getColor(context, R.color.color_6e9fff)
                )
            }
            if (circleImage2.visibility == VISIBLE) {
                DrawableCompat.setTint(
                    circleImage2.drawable,
                    ContextCompat.getColor(context, R.color.color_55c6da)
                )
            }
    }

    private fun checkSpecificLocales(dayOfTheWeekString: String, i: Int): String {
        // Set Wednesday as "X" in Spanish Locale.getDefault()
        var dayOfTheWeekString = dayOfTheWeekString
        dayOfTheWeekString = if (i == 4 && Locale.getDefault().country == "ES") {
            "X"
        } else {
            dayOfTheWeekString.substring(0, 1).uppercase(Locale.getDefault())
        }
        return dayOfTheWeekString
    }
    // ************************************************************************************************************************************************************************
    // * Public calendar methods
    // ************************************************************************************************************************************************************************
    /**
     * Set an specific calendar to the view
     *
     * @param calendar
     */
    fun setCalendar(calendar: Calendar?) {
        currentCalendar = calendar
        updateView()
        checkRightButtonVisibility()
    }

    /**
     * Update the calendar view
     */
    fun updateView() {
        setUpMonthLayout()
        setUpWeekDaysLayout()
        setUpDaysOfMonthLayout()
        setUpDaysInCalendar()
        markDayAsCurrentDay()
    }

    fun setShortWeekDays(shortWeekDays: Boolean) {
        this.shortWeekDays = shortWeekDays
    }

    /**
     * Clear the view of marks and selections
     */
    fun clearCalendar() {
        updateView()
    }

    fun markCircleImage1(calendar: Calendar) {
        currentCalendar?.let {
            if (it.get(Calendar.YEAR) == calendar.get(Calendar.YEAR) && it.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)) {
                //同一个月的才画
                val circleImage1 = getCircleImage1(calendar)
                circleImage1.visibility = VISIBLE
                DrawableCompat.setTint(
                    circleImage1.drawable,
                    ContextCompat.getColor(context, R.color.color_6e9fff)
                )
            }
          }
        }

    fun showDateTitle(show: Boolean) {
        if (show) {
            robotoCalendarMonthLayout?.visibility = VISIBLE
        } else {
            robotoCalendarMonthLayout?.visibility = GONE
        }
    }

    private val markDays: MutableList<Long> = ArrayList()

    /**
     * 添加标记的天数
     *
     * @param markDays
     */
    fun addMarkDays(markDays: List<Long>) {
        this.markDays.addAll(markDays)
        updateMark()
    }

    private fun updateMark() {
        for (markDay in markDays) {
            val calendar: Calendar = Calendar.getInstance()
            calendar.timeInMillis = markDay
            markCircleImage1(calendar)
        }
        currentSelectedDay?.let {
            setSelectedDay(it.timeInMillis)
        }
    }

    // ************************************************************************************************************************************************************************
    // * Public interface
    // ************************************************************************************************************************************************************************
    abstract class OnCalendarClickListener {
        /**
         * 点击某一天了
         *
         * @param daySelectedCalendar
         */
        abstract fun onDayClick(daySelectedCalendar: Calendar?)

        /**
         * 没有标记的回调
         *
         * @param daySelectedCalendar
         */
        open fun onDayNotMarkClick(daySelectedCalendar: Calendar?) {}

        /**
         * 点击右边箭头
         */
        open fun onRightButtonClick() {}

        /**
         * 点击左边箭头
         */
        open fun onLeftButtonClick() {}
    }

    fun setOnCalendarClickListener(onCalendarClickListener: OnCalendarClickListener?) {
        this.onCalendarClickListener = onCalendarClickListener
    }

    // ************************************************************************************************************************************************************************
    // * Event handler methods
    // ************************************************************************************************************************************************************************
    private val onDayOfMonthClickListener =
        OnClickListener { view ->
            currentCalendar?.let {
                // Extract day selected
                val dayOfTheMonthContainer = view as ViewGroup
                var tagId = dayOfTheMonthContainer.tag as String
                tagId = tagId.substring(DAY_OF_THE_MONTH_LAYOUT.length, tagId.length)
                val dayOfTheMonthText =
                    view.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT + tagId) as TextView

                // Extract the day from the text
                val calendar: Calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, it.get(Calendar.YEAR))
                calendar.set(Calendar.MONTH, it.get(Calendar.MONTH))
                calendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dayOfTheMonthText.text.toString()))
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                if (currentTimeMillis >= calendar.timeInMillis) {
                    currentSelectedDay = calendar
                    //只能选择今天之前的日期
                    markDayAsSelectedDay(calendar)
                    // Fire event
                    onCalendarClickListener?.let {
                        var isExisted = false
                        for (markDay in markDays) {
                            if (TimeUtils.getTodayStart(markDay) == calendar.timeInMillis) {
                                isExisted = true
                                break
                            }
                        }
                        if (isExisted) {
                            //由于点击之后马上关闭的话看不出选中的效果，所以延迟100ms再回调点击事件
                            postDelayed({ it.onDayClick(calendar) }, 100)
                        } else {
                            postDelayed({ it.onDayNotMarkClick(calendar) }, 100)
                        }
                    }
                }
            }
        }

    private val onDayOfMonthLongClickListener =
        OnLongClickListener { view -> // Extract day selected
            currentCalendar?.let {
                val dayOfTheMonthContainer = view as ViewGroup
                var tagId = dayOfTheMonthContainer.tag as String
                tagId = tagId.substring(DAY_OF_THE_MONTH_LAYOUT.length, tagId.length)
                val dayOfTheMonthText =
                    view.findViewWithTag<View>(DAY_OF_THE_MONTH_TEXT + tagId) as TextView

                // Extract the day from the text
                val calendar: Calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, it.get(Calendar.YEAR))
                calendar.set(Calendar.MONTH, it.get(Calendar.MONTH))
                calendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dayOfTheMonthText.text.toString()))
                markDayAsSelectedDay(calendar)

                // Fire event
                onCalendarClickListener?.onDayNotMarkClick(calendar)
            }
            true
        }

    // ************************************************************************************************************************************************************************
    // * Getter methods
    // ************************************************************************************************************************************************************************
    private fun getDayOfMonthBackground(currentCalendar: Calendar): ViewGroup {
        return getView(DAY_OF_THE_MONTH_BACKGROUND, currentCalendar) as ViewGroup
    }

    private fun getDayOfMonthText(currentCalendar: Calendar): TextView {
        return getView(DAY_OF_THE_MONTH_TEXT, currentCalendar) as TextView
    }

    private fun getCircleImage1(currentCalendar: Calendar): ImageView {
        return getView(DAY_OF_THE_MONTH_CIRCLE_IMAGE_1, currentCalendar) as ImageView
    }

    private fun getCircleImage2(currentCalendar: Calendar): ImageView {
        return getView(DAY_OF_THE_MONTH_CIRCLE_IMAGE_2, currentCalendar) as ImageView
    }

    private fun getDayIndexByDate(currentCalendar: Calendar): Int {
        val monthOffset = getMonthOffset(currentCalendar)
        val currentDay: Int = currentCalendar.get(Calendar.DAY_OF_MONTH)
        return currentDay + monthOffset
    }

    private fun getMonthOffset(currentCalendar: Calendar): Int {
        val calendar: Calendar = Calendar.getInstance()
        calendar.time = currentCalendar.time
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        val firstDayWeekPosition: Int = calendar.firstDayOfWeek
        val dayPosition: Int = calendar.get(Calendar.DAY_OF_WEEK)
        return if (firstDayWeekPosition == 1) {
            dayPosition - 1
        } else {
            if (dayPosition == 1) {
                6
            } else {
                dayPosition - 2
            }
        }
    }

    private fun getWeekIndex(weekIndex: Int, currentCalendar: Calendar): Int {
        val firstDayWeekPosition: Int = currentCalendar.firstDayOfWeek
        return if (firstDayWeekPosition == 1) {
            weekIndex
        } else {
            if (weekIndex == 1) {
                7
            } else {
                weekIndex - 1
            }
        }
    }

    private fun getView(key: String, currentCalendar: Calendar): View? {
        val index = getDayIndexByDate(currentCalendar)
        return rootView?.findViewWithTag(key + index)
    }

    /**
     * 检查右边按钮是否应该显示
     * 如果当前显示的月份大于等于系统当前月份，则隐藏右边按钮
     */
    private fun checkRightButtonVisibility() {
        val systemCalendar: Calendar = Calendar.getInstance()
        if (!isHideRightBtn) return

        currentCalendar?.let {
            // 比较年份
            if (it.get(Calendar.YEAR) > systemCalendar.get(Calendar.YEAR)) {
                rightButton?.visibility = INVISIBLE
                return
            }

            // 如果年份相同，比较月份
            if (it.get(Calendar.YEAR) == systemCalendar.get(Calendar.YEAR) &&
                it.get(Calendar.MONTH) >= systemCalendar.get(Calendar.MONTH)
            ) {
                rightButton?.visibility = INVISIBLE
            } else {
                // 如果不是限制月份模式，则显示右边按钮
                if (!isLimitMonth) {
                    rightButton?.visibility = VISIBLE
                }
            }
        }
    }

    companion object {
        private const val DAY_OF_THE_WEEK_TEXT = "dayOfTheWeekText"
        private const val DAY_OF_THE_WEEK_LAYOUT = "dayOfTheWeekLayout"
        private const val DAY_OF_THE_MONTH_LAYOUT = "dayOfTheMonthLayout"
        private const val DAY_OF_THE_MONTH_TEXT = "dayOfTheMonthText"
        private const val DAY_OF_THE_MONTH_BACKGROUND = "dayOfTheMonthBackground"
        private const val DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 = "dayOfTheMonthCircleImage1"
        private const val DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 = "dayOfTheMonthCircleImage2"
    }
}